<?php

namespace App\Http\Controllers\Api;

use App\Services\AuthorizationSocialService;
use Illuminate\Http\Request;
use App\Http\Requests\Api\SocialAuthorizationRequest;

class AuthorizationsController extends Controller
{
    public function showAppid($type,Request $request){
        //
        if ($type=="wechat"){
            $appid = config("wechat.official_account.default.app_id");
        }
        $data = [
            "appid"=>$appid,
        ];
        return response()->json($data)->setStatusCode(200);
    }
    public function socialStore($type, SocialAuthorizationRequest $request,AuthorizationSocialService $authorizationSocialService)
    {
        //获取第三方的标识，包括unionid、openid、sessionkey等
        $openid_unionid_arr = $authorizationSocialService->getThirdId($type,$request);
        //判断用户是否已存在
        $user = $authorizationSocialService->isUserExist($type,$openid_unionid_arr);
        //存在就更新用户信息，否则携带第三方必要数据生成一个key
        if ($user){
            $authorizationSocialService->updateUserInfo($type,$openid_unionid_arr,$user);
        }else{
            $key = $authorizationSocialService->CreateThirdIdKey($type,$openid_unionid_arr);
        }
        //找到用户了，直接返回token信息
        if ($user){
            //微信登录成功
            $token = auth('api')->login($user);
            return $this->respondWithToken($token)->setStatusCode(201);
        }else{
            //没找到用户，返回key进行绑定注册
            return response()->json(['key'=>$key])->setStatusCode(200);
        }

    }

    public function update()
    {
        $token = auth('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        auth('api')->logout();
        return response(null, 204);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
//            'expires_in' => 10
        ]);
    }
}
